package net.siufung.web.aop.aspect;

import lombok.AllArgsConstructor;
import net.siufung.core.exception.BizServiceException;
import net.siufung.core.result.ResultFail;
import net.siufung.web.aop.annotation.AutoPermit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * @author 陈建峰
 * @date 2022/10/18 6:25 下午
 * @since V1.0.0
 */
@Aspect
@AllArgsConstructor
public class AutoPermitAspect {

    private final DefaultListableBeanFactory defaultListableBeanFactory;

    @Before("@annotation(autoPermit)")
    public void autoPermit(JoinPoint joinPoint, AutoPermit autoPermit) {
        String permitValue = autoPermit.value();
        SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
        Expression expression = spelExpressionParser.parseExpression(permitValue);
        StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext();
        standardEvaluationContext.setBeanResolver(new BeanFactoryResolver(defaultListableBeanFactory));
        Boolean result = expression.getValue(standardEvaluationContext, Boolean.class);
        if(Boolean.FALSE.equals(result)){
            throw new BizServiceException(ResultFail.AUTH_ACCESS_DENIED);
        }
    }
}
